package com.pbd.server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6573452723984461795L;

	// private static String FILE_SEPERATOR =
	// System.getProperty("file.separator");

	private static String DESTINATION_DIR_PATH = "/UploadFile";

	private static final String TMP_DIR_PATH = "/temp";
	private File tmpDir;
	private File destinationDir;
	private File photoDir;
	private File videoDir;
	private File docDir;
	private File importDir;
	private File logoDir;

	public void init(ServletConfig config) throws ServletException {
		System.out.println("Init........");
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.isDirectory())
			tmpDir.mkdir();

		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		if (realPath != null) {
			destinationDir = new File(realPath);
			if (!destinationDir.isDirectory())
				destinationDir.mkdir();
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		if (request.getHeader("descpath") != null)
			response.setContentType("application/xml");
		else
			response.setContentType("text/plain");
		out.println();

		System.out.println("Inside Servlet Process........");

		if (request.getHeader("path") != null) {
			deleteFile(request.getHeader("path"), out);
		}

		else if (request.getHeader("descpath") != null) {
			showFile(request.getHeader("descpath"), out);
		} else {

			// if(request.getParameter("uploaderId")!=null ){}

			DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
			/*
			 * Set the size threshold, above which content will be stored on
			 * disk.
			 */
			fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
			/*
			 * Set the temporary directory to store the uploaded files of size
			 * above threshold.
			 */
			fileItemFactory.setRepository(tmpDir);

			ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

			System.out.println(request);
			try {
				/*
				 * Parse the request
				 */
				List<FileItem> items = uploadHandler.parseRequest(request);
				System.out.println(items.size());
				Iterator<FileItem> itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();

					if (item.isFormField()) {
						out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
					} else {

						// Handle Uploaded files.
						System.out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());
						/*
						 * Write file to the ultimate location.
						 */
						String contentType = item.getContentType();
						String fileWritedPath = null;
						String uploaderId = request.getParameter("uploaderId");
						if (uploaderId != null && uploaderId.length() > 0 && request.getParameter("uploadFor") == null) {

							System.out.println("Inside uploaderId not null part");

							File uploaderLocationId = new File(request.getParameter("uploaderId"));

							if (contentType.equals("image/png") || contentType.equals("image/jpeg") || contentType.equals("image/gif")) {

								if (uploaderLocationId.isDirectory()) {

									if (photoDir.isDirectory()) {
										fileWritedPath = writeFile(photoDir, item);
									} else {
										photoDir.mkdir();
										fileWritedPath = writeFile(photoDir, item);
									}
								} else {
									uploaderLocationId = new File(destinationDir, uploaderLocationId.toString());
									uploaderLocationId.mkdir();
									photoDir = new File(uploaderLocationId, "photos");
									photoDir.mkdir();
									fileWritedPath = writeFile(photoDir, item);
								}

							} else if (contentType.equalsIgnoreCase("video/mpeg") || contentType.equalsIgnoreCase("video/mp4") || contentType.equalsIgnoreCase("video/webm") || contentType.equalsIgnoreCase("video/avi") || contentType.equalsIgnoreCase("application/octet-stream")) {

								if (uploaderLocationId.isDirectory()) {

									if (videoDir.isDirectory()) {
										fileWritedPath = writeFile(videoDir, item);
									} else {
										videoDir.mkdir();
										fileWritedPath = writeFile(videoDir, item);
									}
								} else {
									uploaderLocationId = new File(destinationDir, uploaderLocationId.toString());
									uploaderLocationId.mkdir();
									videoDir = new File(uploaderLocationId, "videos");
									videoDir.mkdir();
									fileWritedPath = writeFile(videoDir, item);
								}
							} else if (contentType.equals("application/msword") || contentType.equals("application/vnd.ms-excel") || contentType.equals("application/pdf")) {
								if (uploaderLocationId.isDirectory()) {

									if (docDir.isDirectory()) {
										fileWritedPath = writeFile(docDir, item);

									} else {
										docDir.mkdir();
										fileWritedPath = writeFile(docDir, item);
									}
								} else {
									uploaderLocationId = new File(destinationDir, uploaderLocationId.toString());
									uploaderLocationId.mkdir();
									docDir = new File(uploaderLocationId, "Documents");
									docDir.mkdir();
									fileWritedPath = writeFile(docDir, item);
								}

							}
						} else if (request.getParameter("uploadFor") != null && request.getParameter("uploadFor").equals("import")) {

							if (importDir != null && importDir.isDirectory()) {

								fileWritedPath = writeFile(importDir, item);

							} else {
								importDir = new File(destinationDir, "ImportedFiles");

								importDir.mkdir();
								System.err.println("import Dir ::" + importDir.getAbsolutePath());
								fileWritedPath = writeFile(importDir, item);
							}

						} else {
							// If file upload is for logo
							System.out.println("Inside uploaderId null part");

							if (contentType.equals("image/png") || contentType.equals("image/jpeg") || contentType.equals("image/gif")) {
								if (logoDir != null && logoDir.isDirectory()) {
									fileWritedPath = writeFile(destinationDir, item);
								} else {

									logoDir = new File(destinationDir, "Logo");

									logoDir.mkdir();
									System.err.println("Logo Dir ::" + logoDir.getAbsolutePath());
									fileWritedPath = writeFile(logoDir, item);
								}
							}
						}
						response.setStatus(HttpServletResponse.SC_OK);
						out.write(fileWritedPath);
						response.flushBuffer();
					}
					out.close();
				}
			} catch (FileUploadException ex) {
				log("Error encountered while parsing the request", ex);
			} catch (Exception ex) {
				log("Error encountered while uploading file", ex);
			}

		}
	}

	private void deleteFile(String filePath, PrintWriter out) {
		try {

			String path = getServletContext().getRealPath(filePath);
			File fileToBeDeleted = new File(path);
			System.out.println(fileToBeDeleted);
			if (fileToBeDeleted.isFile()) {
				fileToBeDeleted.delete();
				out.write("File Successfully deleted");
			} else {
				out.write("Requested resource is not a file");
			}

		} catch (Exception ex) {
			out.write("Error encountered while uploading file" + ex);
		}
	}

	private void showFile(String filePath, PrintWriter out) {
		InputStream input = null;
		try {

			input = getServletContext().getResourceAsStream(filePath);
			int ch;
			while ((ch = input.read()) != -1) {
				out.write((char) ch);
			}

		} catch (IOException ex) {
			out.write("Error encountered while uploading file" + ex);
		} finally {
			if (input != null)
				try {
					input.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	private String writeFile(File dirName, FileItem item) {
		try {
			File file = new File(dirName, item.getName());

			item.write(file);
			return dirName + "\\" + item.getName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
